#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys

from scpy.xawesome_time import now
import gevent
import gevent.monkey
gevent.monkey.patch_all()
from crawler import camcard
import utils
import qichacha_service
import saic_service

reload(sys)
sys.setdefaultencoding("utf-8")


def deal_result(doc, source):
    if not isinstance(doc, dict):
        return None
    doc['source'] = source
    return doc


def search(mode, key, province=None, forced_latest=False, strict_mode=False):
    key = key.replace(u'(', u'（').replace(u')', u'）')
    province = unicode(province)
    return mode(key, province, forced_latest, strict_mode)


def search_saic(key, province=None, forced_latest=False, strict_mode=False):
    return deal_result(saic_service.search(key, province, forced_latest, strict_mode), 'saic')


def search_qcc(key, province=None, forced_latest=False, strict_mode=False):
    return deal_result(qichacha_service.search(key, province, forced_latest, strict_mode), 'qcc')


def search_mpw(key, province=None, forced_latest=False, strict_mode=False):
    return deal_result(camcard.search(key), 'mpw')


def search_all(key, province=None, forced_latest=False, strict_mode=False):
    threads = [gevent.spawn(function, key, province, forced_latest, strict_mode) for function in [search_saic, search_qcc, search_mpw]]
    print 'now :', now()
    gevent.joinall(threads, timeout=30)
    print 'now :', now()

    result = {}
    for thread in threads:
        if thread.successful() and thread.value:
            result[thread.value['source']] = thread.value
    return result


def search_one_by_one(key, province=None, forced_latest=False, strict_mode=False):
    try:
        result = search_qcc(key, province, forced_latest, strict_mode)
        if result:
            return result
    except:
        pass
    try:
        result = search_mpw(key, province, forced_latest, strict_mode)
        if result:
            return result
    except:
        pass
    try:
        result = search_saic(key, province, forced_latest, strict_mode)
        if result:
            return result
    except:
        pass
    return None

MODE_ALL = search_all
MODE_SAIC = search_saic
MODE_QCC = search_qcc
MODE_MPW = search_mpw
MODE_OBO = search_one_by_one


def checkname(key):
    try:
        data = camcard.company_list(key)
        if not data['data']['items']:
            return None
        result = []
        for item in data['data']['items']:
            name = item['name'].strip()
            try:
                utils.DB['companyNames'].insert({'_id': name})
            except Exception, e:
                # print e
                pass  # saved
            result.append({'companyName': name})
        # return [{'companyName': item['name']} for item in data['data']['items']]
        return result
    except:
        return None
